﻿using MediatR;
using Medical.Api.Write.Application.Command.DepartmentManagement.Adopted;
using Medical.Domain.DepartmentInfo;
using Medical.ErrorCode;
using Medical.Interstructrue;
using Medical.Interstructrue.Base;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using System;
using System.Threading;
using System.Threading.Tasks;

namespace Medical.Api.Write.Application.Handler.DepartmentManagement.Adopted
{
    /// <summary>
    /// 更新领用申请状态处理程序
    /// </summary>
    public class UpdateAdoptedStatusCommandHandler : IRequestHandler<UpdateAdoptedStatusCommands, ApiResult<int>>
    {
        private readonly ILogger<UpdateAdoptedStatusCommandHandler> logger;
        private readonly IBaseRepository<TouseTable> touseRep;
        private readonly MedicalDbContext dbContext;

        /// <summary>
        /// 构造函数，注入所需依赖
        /// </summary>
        /// <param name="logger">日志记录器</param>
        /// <param name="touseRep">领用表仓储</param>
        /// <param name="dbContext">数据库上下文</param>
        public UpdateAdoptedStatusCommandHandler(
            ILogger<UpdateAdoptedStatusCommandHandler> logger,
            IBaseRepository<TouseTable> touseRep,
            MedicalDbContext dbContext)
        {
            this.logger = logger;
            this.touseRep = touseRep;
            this.dbContext = dbContext;
        }

        /// <summary>
        /// 处理更新领用申请状态命令
        /// </summary>
        /// <param name="request">更新领用申请状态命令</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>API结果</returns>
        public async Task<ApiResult<int>> Handle(UpdateAdoptedStatusCommands request, CancellationToken cancellationToken)
        {
            try
            {
                logger.LogInformation("开始处理领用申请状态更新，ID：{Id}，新状态：{Status}", request.Id, request.TouseStatus);
                
                // 检查要修改的领用申请记录是否存在
                var existingTouse = await touseRep.GetModelAsync(request.Id);
                if (existingTouse == null)
                {
                    logger.LogWarning("未找到ID为{Id}的领用申请记录", request.Id);
                    return new ApiResult<int>()
                    {
                        Code = ApiEnums.NotFound,
                        Data = 0,
                        Msg = $"未找到ID为{request.Id}的领用申请记录"
                    };
                }
                
                // 先分离实体，避免跟踪冲突
                dbContext.Entry(existingTouse).State = EntityState.Detached;
                
                // 更新状态信息
                existingTouse.TouseStatus = request.TouseStatus;
                existingTouse.UpdateTime = DateTime.Now;
                
                // 更新领用申请
                touseRep.Update(existingTouse);
                await dbContext.SaveChangesAsync(cancellationToken);
                
                logger.LogInformation("成功更新领用申请状态，ID：{0}，新状态：{1}", request.Id, request.TouseStatus);
                return new ApiResult<int>()
                {
                    Code = ApiEnums.Success,
                    Data = request.Id,
                    Msg = "成功更新领用申请状态"
                };
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "更新领用申请状态时发生错误：{0}", ex.Message);
                return new ApiResult<int>()
                {
                    Code = ApiEnums.Fail,
                    Data = 0,
                    Msg = $"更新领用申请状态失败：{ex.Message}"
                };
            }
        }
    }
}
